/*
 * @Author: Jiraiya
 * @Date: 2020-04-07 18:54:15
 * @LastEditors: Jiraiya
 * @LastEditTime: 2020-04-08 11:09:57
 * @Description: 
 */
class hash{
    constructor(){
        this.routes = {};
        this.currentUrl = '';
        this.history = [];

        
        this.currentIndex = this.history.length - 1;
        this.backIndex = this.history.length - 1;
        this.refresh = this.refresh.bind(this);
        this.backOff = this.backOff.bind(this);

        this.isBack = false;
        window.addEventListener('load', this.refresh, false);
        window.addEventListener('hashchange', this.refresh, false);
    }

    route(path, callback){
        this.routes[path] = callback || function(){};
    }

    refresh(){
        this.currentUrl = location.hash.slice(1) || '/';
        this.history.push(this.currentUrl);
        this.currentIndex++;
        if(!this.isBack){
            this.backIndex = this.currentIndex;
        }
        this.routes[this.currentUrl]();
        this.isBack = false;
    }

    backOff(){
        this.isBack = true;
        this.backIndex <= 0 ? this.backIndex = 0 : this.backIndex -= 1;
        location.hash = `#${this.history[this.backIndex]}`
    }
}